
import { defineStore } from 'pinia'
import { 
  login as loginApi,
  logout as logoutApi,
  permCode,
  userInfo
 } from '/@/api/auth'

interface UserState {
  token?: string | undefined;
  userId?: string | number | undefined
  name?: string;
  userInfo?: any;
  ext?: any;
  // 用户权限标识
  permList?: Array<String>,
}
export const useUserStore = defineStore('app-user', {
  // 推荐使用 完整类型推断的箭头函数
  state: (): UserState => {
    return {
      // 所有这些属性都将自动推断其类型
      token: '',
      name: '张三',
      userInfo: {},
      ext: {},
      permList: []
    }
  },
  actions: {
    
    setToken(token: string|undefined) {
      this.token = token
    },
    /**
     * 用户名密码登录
     * @param userName 
     * @param password 
     */
    login(userName: string,password: string):Promise<any> {
      return new Promise((resolve,reject)=>{
        loginApi({
          userName,
          password
        }).then(res=>{
          if(res.code === 0) {
            resolve(res.data)
            this.setToken(res.data?.token)
          } else {
            reject(new Error(res.msg || '登录失败'))
          }
          
        }).catch(e=>{
          reject(e)
        })
      })
    },
    logout():Promise<any> {
      return new Promise((resolve,reject)=>{
        logoutApi({}).then(res=>{
          resolve(res)
          this.clearUserCache()
        }).catch(e=>{
          reject(e)
        })
      })
    },
    /**
     * 初始化权限标识
     */
    initPermCode() {
      return new Promise((resolve,reject)=>{
        if(this.getToken) {
          permCode().then(res=>{
            resolve(res)
            this.permList = res.data || []
          }).catch(e=>{
            reject(e)
          })
        } else {
          resolve([])
        }
      })
    },
    /**
     * 清理用户缓存
     */
    clearUserCache() {
      this.setToken(undefined)
      this.userId = undefined
      this.name = undefined
      this.permList = []
      this.userInfo = {}
    },
    /**
     * 判断是否有权限
     * @param code 权限code，多个使用英文逗号分割
     */
    hasPerm(code: string) {
      if(!code) {
        // code 未定义，则有权限
        return true
      }
      // admin===超级管理权限
      if(this.permList?.includes('admin')){
        return true;
      }
      const codeArr: Array<String> = code.split(",")
      return this.permList?.some(item=>{
        return codeArr.includes(item)
      })
    },
    getUserInfo():Promise<any> {
      return new Promise((resolve,reject)=>{
        if(this.getToken) {
          userInfo().then(res=>{
            resolve(res)
            if(res.code === 0) {
              this.userId = res.data.id
              this.name = res.data.realName || res.data.userName
              this.userInfo = res.data
            }
          }).catch(e=>{
            reject(e)
          })
        } else {
          resolve([])
        }
      })
    }
  },
  getters: {
    getToken(): string {
      return this.token || window.localStorage.getItem('token') || ''
    },
    getName(): string {
      return this.name || ''
    }
  },
  persist: {
    storage: localStorage,
    key: "app-user"
  }
})